package servlet;

import bean.Result;
import biz.BizException;
import biz.UserBiz;
import com.google.gson.Gson;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "SaveUserServlet", value = "/SaveUserServlet.s")
public class SaveUserServlet extends HttpServlet {

    UserBiz biz = new UserBiz();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");

        final String uname = request.getParameter("uname");
        final String pwd = request.getParameter("pwd");
        final String email = request.getParameter("email");
        final String phone = request.getParameter("phone");
        final String sex = request.getParameter("sex");
        String image = request.getParameter("image");

        final String uid = request.getParameter("uid");

        Result result;

        try {
            if (uid == null || "".equals(uid)){
                biz.saveUser(uname, pwd, phone, sex, email, image);
            } else {
                biz.modifyUser(uname, pwd, phone, sex, email, uid);
            }
            result = new Result(1, "操作成功！", null);
        } catch (BizException e) {
            e.printStackTrace();
            result = new Result(0, e.getMessage(), null);
        }

        final String json = new Gson().toJson(result);
        response.getWriter().append(json);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
